package com.heima.search.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 联想词表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 自动补全功能，关键字联想功能，使用es优化
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {

        try {
            //2.实例化请求，指定索引库
            SearchRequest searchRequest = new SearchRequest("app_info_article");
            //3.准备DSL
            searchRequest.source().suggest(new SuggestBuilder()
                    .addSuggestion("keyWordSuggest",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(dto.getSearchWords())
                                    .skipDuplicates(true)
                                    .size(10)));

            //1.查询请求对象
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            //4.解析结果
            Suggest suggest = response.getSuggest();
            //5.获取补全名
            CompletionSuggestion keyWordSuggest = suggest.getSuggestion("keyWordSuggest");
            //6.获取options
            List<CompletionSuggestion.Entry.Option> options = keyWordSuggest.getOptions();
            //7.数据封装
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                list.add(option.getText().toString());
            }
            return ResponseResult.okResult(list);

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}

